package com.snail.snailvr.views.fragments;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.snail.snailvr.R;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.LocalVideoRefreshComplete;
import com.snail.snailvr.model.ActionItem;
import com.snail.snailvr.model.Video;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.MediaLibrary;
import com.snail.snailvr.utils.SharedPreferencesUtil;
import com.snail.snailvr.views.adapter.LocalVideoAdapter;
import com.snail.snailvr.widget.HorizontalDividerItemDecoration;
import com.snail.snailvr.widget.MenuPopup;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 本地视频列表
 * Created by snail on 16/3/28.
 */
public class LocalVideosFragment extends BaseToolbarFragment {

    private static final int ORDER_DATA = 0, ORDER_SIZE = 1;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.list)
    RecyclerView mRecyclerView;
    @Bind(R.id.empty_view)
    View mEmptyView;
    private MenuPopup mMenuPopup;
    private Subscription mGetLocalVideosSubscription;
    private List<Video> mLocalVideoLists;
    private LocalVideoAdapter mAdapter;
    private Subscription scanMediSsubscription;
    private boolean isScanning=false;
    private ImageView refreshView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusProvider.getInstance().register(this);
    }

    public LocalVideosFragment() {
    }

    @Override
    protected void handleIntent() {

    }

    @Override
    protected void initView() {
        setupToolbar(mToolbar,getString(R.string.local_file), R.menu.menu_local_video);
        setupRecyclerView();
        getLocalVideos();
        initPopWindow();
        initActionView();
    }

    private void initActionView() {
        MenuItem refreshItem = mToolbar.getMenu().findItem(R.id.action_refresh);
        refreshView = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.refresh_view, mToolbar,false);
        refreshView.setImageResource(R.drawable.ic_localfile_reload);
        refreshItem.setActionView(refreshView);
        refreshView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshMenuItemView();
                scanLocalVideos();
            }
        });
    }

    private void setupRecyclerView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mLocalVideoLists = new ArrayList<>();
        mAdapter = new LocalVideoAdapter(getActivity(), mLocalVideoLists);
        mRecyclerView.setAdapter(mAdapter);
        addDivider();

    }
    protected void addDivider() {
        //TODO 统一addDivider在BaseFragment
        HorizontalDividerItemDecoration horizontalDividerItemDecoration=new HorizontalDividerItemDecoration.Builder(getActivity())
                .paintProvider(mAdapter)
                .visibilityProvider(mAdapter)
                .marginProvider(mAdapter)
                .build();
        horizontalDividerItemDecoration.setBackgroundPaintColor(getResources().getColor(R.color.list_item_color_normal));
        mRecyclerView.addItemDecoration(horizontalDividerItemDecoration);
    }
    private void initPopWindow() {

        mMenuPopup = new MenuPopup(getActivity());
        mMenuPopup.setPopupWidth(getResources().getDimensionPixelSize(R.dimen.order_popup_width));
        mMenuPopup.setItemOnClickListener(mOnItemOnClickListener);

        mMenuPopup.addAction(new ActionItem(getString(R.string.menu_order_data),
                SharedPreferencesUtil.getInstance(getActivity()).getSortOrder().equals(MediaStore.Video.Media.DATE_ADDED)));
        mMenuPopup.addAction(new ActionItem(getString(R.string.menu_order_size),
                SharedPreferencesUtil.getInstance(getActivity()).getSortOrder().equals(MediaStore.Video.Media.SIZE)));
    }


    @Override
    protected void loadData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_local_videos;
    }


    private void getLocalVideos() {
        mGetLocalVideosSubscription = Observable.create(new Observable.OnSubscribe<List<Video>>() {
            @Override
            public void call(Subscriber<? super List<Video>> subscriber) {
                String sortOrder=SharedPreferencesUtil.getInstance(getActivity()).getSortOrder();
                if(sortOrder.equals(MediaStore.Video.Media.DATE_ADDED))
                    sortOrder+=" desc";
                List<Video> videoList = getList(sortOrder);
                subscriber.onNext(videoList);

            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<Video>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<Video> videoList) {
                        LogUtils.d("videoList size="+videoList.size());
                        if (getActivity() != null) {
                            if (videoList.isEmpty()) {
                                showEmpty();
                            } else {
                                hideEmptyView();
                                mLocalVideoLists.clear();
                                mLocalVideoLists.addAll(videoList);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }

    private void hideEmptyView() {
        mEmptyView.setVisibility(View.GONE);
    }

    private void showEmpty() {
        mEmptyView.setVisibility(View.VISIBLE);
    }

    /**
     * 从媒体库获取本地视频
     *
     * @return sortOrder排序方式（时间排序以及大小排序）
     */
    public List<Video> getList(String sortOrder) {
        List<Video> list = null;
        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null,
                null, sortOrder);
        if (cursor != null) {
            list = new ArrayList<>();
            while (cursor.moveToNext()) {
                Video video = new Video(cursor);
                if(video.getLong_duration()>0L)
                    list.add(video);
            }
            cursor.close();
        }
        return list;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusProvider.getInstance().unregister(this);
        if (mGetLocalVideosSubscription != null && !mGetLocalVideosSubscription.isUnsubscribed())
            mGetLocalVideosSubscription.unsubscribe();
        if (scanMediSsubscription != null && !scanMediSsubscription.isUnsubscribed())
            scanMediSsubscription.unsubscribe();

    }

    @Override
    protected boolean onToolbarMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_sort:
                mMenuPopup.show(mToolbar);
                return true;
            case R.id.action_refresh:

                return true;
        }
        return false;
    }

    private void scanLocalVideos() {
        if(!isScanning) {
            isScanning = true;
            scanMediSsubscription = MediaLibrary.scanMedia().subscribe();
        }
    }

    @Subscribe
    public void onRefreshComplete(LocalVideoRefreshComplete event){
        getLocalVideos();
        scanComplete();
    }

    private void scanComplete() {
        isScanning = false;
        hideRefreshAnimation();
    }

    private MenuPopup.OnItemOnClickListener mOnItemOnClickListener = new MenuPopup.OnItemOnClickListener() {

        @Override
        public void onItemClick(ActionItem item, int position) {

            switch (position) {
                case ORDER_DATA:
                    SharedPreferencesUtil.getInstance(getActivity()).setSortOrder(MediaStore.Video.Media.DATE_ADDED);
                    break;
                case ORDER_SIZE:
                    SharedPreferencesUtil.getInstance(getActivity()).setSortOrder(MediaStore.Video.Media.SIZE);
                    break;
            }
            mMenuPopup.updateSelectPosition(position);
            getLocalVideos();
        }
    };


    private void refreshMenuItemView() {
        hideRefreshAnimation();
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.refresh);
        animation.setRepeatMode(Animation.RESTART);
        animation.setRepeatCount(Animation.INFINITE);
        refreshView.startAnimation(animation);
    }

    private void hideRefreshAnimation() {
        if (refreshView != null&&refreshView.getAnimation()!=null) {
            refreshView.getAnimation().cancel();
        }
    }

}
